<template>
	<view class="action-panel" :class="{ 'panel-show': isShow, 'panel-hide': !isShow }">
		<!-- 左侧关闭图标 -->
		<view class="icon-left" @click.stop="handleClose">
			<uni-icons type="closeempty" size="24" color="#666"></uni-icons>
		</view>

		<!-- 中间功能图标组 -->
		<view class="middle-icons">
			<view class="sound" @click.stop="setSound">
				<image class="sound-img" :src="soundState" mode="aspectFill"></image>
			</view>
			<view class="" v-if="chatItem.type !== 'public'" @click.stop="editName">
				<uni-icons type="compose" size="24" color="#666"></uni-icons>
			</view>

			<image class="topimg" :src="chatItem.isTop ? '/static/noTop.png' : '/static/top.png'" mode="aspectFill" @click="handleTop"></image>
			<uni-icons v-if="chatItem.type !== 'public'" @click="delChat" type="trash" size="24" color="#666"></uni-icons>
			<uni-icons v-else @click="invite" type="personadd" size="24" color="#666"></uni-icons>
		</view>

		<!-- 右侧更多图标 -->
		<view class="icon-right" @click="handleMore">
			<uni-icons type="more-filled" size="24" color="#666"></uni-icons>
			<pop-menu :showMenu="isMore" :menu-list="menuList" menu-bg-color="#e2e2e2" item-color="#636363" @menu-click="menuClick"></pop-menu>
		</view>
		<input-dialog :isShow.sync="showDialog" :placeholder="placeholder" :title="title" @confirm="confirm"></input-dialog>
	</view>
</template>

<script>
import { getSurroundingGrids } from '../utils/getSurroundingGrids';
import * as msgAction from '@/utils/msgAction.js';
import popMenu from './popMenu.vue';
import soundManger from '../utils/soundManger';
import Favorite from '../utils/favoriteClass';
import InputDialog from './InputDialog.vue';
const friend = uniCloud.importObject('friend', { customUI: true });

export default {
	name: 'topTool',
	components: {
		InputDialog,
		popMenu
	},
	props: {
		isShow: {
			type: Boolean,
			default: false
		},
		chatItem: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			favoriteManger: null,
			title: '输入内容',
			placeholder: '请输入收藏名',
			currentName: '',
			soundmanger: null,
			showDialog: false,

			sound: 0,
			isMore: false,
			soundMap: {
				0: '/static/sound.png',
				1: '/static/vibration.png',
				2: '/static/nosound.png'
			},
			menuList: [
				{ label: '地图搜索', value: 'toMap' },
				{ label: '地名输入', value: 'keyWord' }
			]
		};
	},

	computed: {
		soundState() {
			// 非收藏类型直接返回默认图标
			let id = '';
			if (this.chatItem?.type === 'favorite') {
				id = this.chatItem.favorite_id;
			} else if (this.chatItem?.type === 'group') {
				id = this.chatItem.groupId;
			} else if (this.chatItem?.type === 'person') {
				id = this.chatItem.userId;
			}
			const sound = new soundManger();

			const state = sound.getState(id);
			console.log('状态', state);
			if (state === 2) {
				return '/static/sound.png';
			} else if (state === 0) {
				return '/static/nosound.png';
			} else if (state === 1) {
				return '/static/vibration.png';
			} else {
				return '/static/sound.png';
			}
		}
	},

	watch: {
		soundState: {
			handler(newval) {
				console.log(newval);
			},
			immediate: true,
			deep: true
		}
	},

	mounted() {},
	methods: {
		handleClose() {
			this.$emit('close');
		},
		handleMore() {
			this.isMore = true;
			this.$emit('more-click');
		},
		async confirm(name) {
			if (this.chatItem.type === 'favorite') {
				const location = this.$store.state.msg.location;
				const storeData = this.$store.state.msg;
				const favoriteManger = new Favorite(location, storeData);
				favoriteManger.rename(this.chatItem.favorite_id, name);
				uni.$emit('reload');
			}
			if ((this.chatItem.type = 'person')) {
				const userId = this.$store.state.msg.user.userId;
				console.log("55555",this.chatItem);
				const friendUserId = this.chatItem.userId;
				const remarkName = name;
				const res = await friend.editFriendRemarkName({ userId, friendUserId, remarkName });
				console.log("22222",res);
				if (res.success) {
					uni.showToast({
						title:'更新成功',
						position:'center'
					})
					uni.$emit('reload');
				} else {
					uni.showToast({
						title: res.message,
						position: 'center'
					});
				}
			}
		},

		menuClick(e) {
			console.log(e);
			switch (e.item.value) {
				case 'toMap':
					{
						uni.navigateTo({
							url: '/pages/main/main'
						});
					}
					break;
				default:
					uni.showToast({
						title: '功能完善中',
						position: 'center',
						icon: 'none'
					});
			}
		},
		editName() {
			switch (this.chatItem.type) {
				case 'favorite':
					{
						(this.placeholder = '输入位置备注名称'), (this.title = '备注收藏点名称'), (this.showDialog = true);
					}
					break;
				case 'group':
					{
						uni.navigateTo({
							url: `/pages/groupDetail/groupDetail?id=${this.chatItem.data?.groupId}`
						});
					}
					break;
				case 'person':
					{
						(this.placeholder = '输入好友注备'), (this.title = '好友备注'), (this.showDialog = true);
					}
					break;
				default: {
				}
			}
		},
		//删除会话
		delChat() {
			const res = uni.getStorageSync('lastStore');
			if (!res || !res.chatList) return; // 容错：避免存储为空或无chatList的情况

			// 根据类型映射唯一标识字段
			const typeKeyMap = {
				favorite: 'favorite_id',
				person: 'userId',
				group: 'groupId'
			};

			// 获取当前项的类型和对应唯一标识
			const { type } = this.chatItem;
			const key = typeKeyMap[type];
			if (!key) return; // 容错：未知类型不处理

			// 过滤掉与当前项标识相同的元素
			const newList = res.chatList.filter((item) => {
				return item[key] !== this.chatItem[key]; // 自动兼容item无key的情况（返回true，不过滤）
			});

			// 根据类型清理对应消息的未读状态
			try {
				if (type === 'favorite') {
					console.log('是否收藏', this.chatItem);
					// 获取收藏列表
					const favorites = this.$store.state.msg.user.favorite || [];
					// 找到当前收藏项（优化：使用find替代filter，更高效）
					const currentFavorite = favorites.find((item) => item.favorite_id === this.chatItem.favorite_id);
					console.log('是否找出我的收藏', currentFavorite);
					if (currentFavorite) {
						const radius = currentFavorite.config?.radius || 5;
						const grids = getSurroundingGrids(this.chatItem.favorite_id, radius);
						// 遍历网格清理未读
						for (const grid of grids) {
							const storageKey = `msg_public_${grid}`;
							const msgs = uni.getStorageSync(storageKey) || []; // 容错：默认空数组

							msgs.forEach((msg) => {
								// 修正：forEach拼写错误
								if (!msg.isRead) {
									msgAction.clearUnRead(msg);
								}
							});
							// 若消息有修改，需要重新存储（根据clearUnRead是否修改原对象决定）
							uni.setStorageSync(storageKey, msgs);
						}
					}
				} else if (type === 'person') {
					const storageKey = `msg_person-${this.chatItem.userId}`;
					const msgs = uni.getStorageSync(storageKey) || [];
					msgs.forEach((msg) => {
						// 修正：forEach拼写错误
						if (!msg.isRead) {
							msgAction.clearUnRead(msg);
						}
					});
					uni.setStorageSync(storageKey, msgs);
				} else if (type === 'group') {
					const storageKey = `msg_group_${this.chatItem.groupId}`;
					const msgs = uni.getStorageSync(storageKey) || [];
					msgs.forEach((msg) => {
						// 修正：forEach拼写错误
						if (!msg.isRead) {
							msgAction.clearUnRead(msg);
						}
					});
					uni.setStorageSync(storageKey, msgs);
				}
			} catch (err) {
				console.error('清理未读状态失败：', err); // 捕获异常，避免流程中断
			}
			console.log('最后存储', { chatList: newList });
			// 重新存储更新后的聊天列表
			uni.setStorageSync('lastStore', { chatList: newList });
			this.$emit('delChat', true);
		},

		handleTop() {
			this.$emit('handleTop');
		},

		//声音设置
		setSound() {
			this.sound++;
			const soundmanger = new soundManger();
			const sound = this.sound % 3;
			console.log(sound);
			console.log(this.chatItem);
			if (this.chatItem.type === 'favorite') {
				soundmanger.setState(this.chatItem.favorite_id, sound);
			} else if (this.chatItem.type === 'group') {
				soundmanger.setState(this.chatItem.groupId, sound);
			} else if (this.chatItem.type === 'person') {
				soundmanger.setState(this.chatItem.userId, sound);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
/* 组件容器：屏宽、固定高度、顶部固定 */
.action-panel {
	width: 750rpx;
	height: 135rpx;
	position: fixed;
	top: 0; /* 改为顶部固定 */
	left: 0;
	right: 0;
	display: flex;
	align-items: flex-end; /* 图标整体靠下对齐 */
	justify-content: space-between;
	padding: 0 30rpx 30rpx; /* 底部内边距20rpx，实现图标离底部20rpx */
	background-color: #fff;
	border-bottom-left-radius: 20rpx; /* 改为底部圆角 */
	border-bottom-right-radius: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05); /* 阴影向下 */
	transform-style: preserve-3d;
	transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.3s;
	pointer-events: none;
}

/* 隐藏状态：向上翻盖（沿顶部中心轴旋转-90度） */
.panel-hide {
	transform: rotateX(-90deg);
	transform-origin: top center; /* 旋转轴改为顶部中心 */
	opacity: 0;
	pointer-events: none;
}

/* 显示状态：向下翻开（恢复初始位置） */
.panel-show {
	transform: rotateX(0deg);
	transform-origin: top center;
	opacity: 1;
	pointer-events: none;
}

/* 左侧关闭图标 */
.icon-left {
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	pointer-events: auto;
}
.sound {
	width: 40rpx;
	height: 40rpx;
	border-radius: 20rpx;
	pointer-events: auto;
	.sound-img {
		width: 40rpx;
		height: 40rpx;
	}
}
.topimg {
	width: 30rpx;
	height: 30rpx;
}
/* 中间图标组：横向居中，均匀分布 */
.middle-icons {
	display: flex;
	align-items: center;
	gap: 60rpx;
	flex: 1;
	justify-content: center;
	pointer-events: auto;
}

.middle-icons uni-icons {
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	pointer-events: auto;
}

/* 右侧更多图标 */
.icon-right {
	position: relative;
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	margin-right: 50rpx;
	pointer-events: auto;
}
</style>
